package com.example.ivideo_2211a.search

import androidx.lifecycle.viewModelScope
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.example.common.mvi.BaseViewModel
import com.example.common.mvi.NetworkResult
import com.example.common.mvi.Res
import com.google.gson.Gson
import kotlinx.coroutines.launch

class SearchViewModel: BaseViewModel<SearchIntent, SearchViewState, SearchResult>() {
    override suspend fun handleIntent(intent: SearchIntent) {
       when(intent){
           is SearchIntent.Search -> {
               searchVideo(intent.keyWord,intent.page,intent.pageSize)
           }
       }
    }
    fun searchVideo(keyWord:String, page:Int,pageSiez: Int){

        viewModelScope.launch {
            val result = SearchRepository().getServiceVideo(keyWord,page,pageSiez)
            result.collect({
                when(it){
                    is NetworkResult.Success -> {
                        try {
                            if (it.data.data.isEmpty())return@collect
                            updateState(SearchViewState(videos = it.data.data, isLoading = true, ))
                        } catch (e: Exception) {
                            ToastUtils.showShort(e.message.toString())
                        }
                    }
                    is NetworkResult.Error -> {

                    }
                    NetworkResult.Loading -> {

                    }
                }
            })
        }
    }
    override fun initialState()=SearchViewState()
}